# coding: utf-8
import logging

from django.contrib import messages
from django.contrib.auth import logout as django_logout
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import RegisterForm, LoginForm, ProfileForm, ChangePasswordForm

def register(request, form_class=RegisterForm, template_name='accounts/register.html'):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            form.register()
            messages.success(request, u'用户注册成功')
            return HttpResponseRedirect("/")
    else:
        form = form_class()
    return render_to_response(template_name, {
            'form': form,
        }, context_instance=RequestContext(request)
    )

def login(request, form_class=LoginForm, template_name='accounts/login.html'):
    if request.method == 'POST':
        form = form_class(request.POST)
        if form.is_valid():
            user = form.login(request)
            if user is not None:
                redirect_to = request.REQUEST.get('next', '')
                if redirect_to:
                    if '//' in redirect_to and re.match(r'[^\?]*//', redirect_to):
                        return HttpResponseRedirect('/')
                    return HttpResponseRedirect(redirect_to)
                return HttpResponseRedirect('/sa/')
    else:
        form = form_class()
    return render_to_response(template_name, {
            'form': form,
        }, context_instance=RequestContext(request)
    )

def logout(request):
    django_logout(request)
    return HttpResponseRedirect('/accounts/login/')

def edit(request, template_name='accounts/profile.html'):
    if request.method == 'POST':
        form = ProfileForm(request.user, request.POST)
        if form.is_valid():
            form.save()
            messages.success(request, u'已成功修改用户信息')
            return HttpResponseRedirect('/accounts/edit/')
    profile_form = ProfileForm(request.user)
    chgpwd_form = ChangePasswordForm(request.user)
    return render_to_response(template_name, {
            'profile_form': profile_form,
            'chgpwd_form': chgpwd_form,
        }, context_instance=RequestContext(request)
    )

def chg_password(request, template_name='accounts/profile.html'):
    if request.method == 'POST':
        chgpwd_form = ChangePasswordForm(request.user, request.POST)
        if chgpwd_form.is_valid():
            chgpwd_form.change_password()
            messages.success(request, u'已成功修改密码')
            return HttpResponseRedirect('/accounts/edit/')
    else:
        chgpwd_form = ProfileForm(request.user)
    profile_form = ProfileForm(request.user)
    return render_to_response(template_name, {
            'profile_form': profile_form,
            'chgpwd_form': chgpwd_form,
        }, context_instance=RequestContext(request)
    )

